//
//  UINavigationItem+CustomBackBarItem.m
//  WXPark
//
//  Created by DaiYu on 15/9/22.
//  Copyright © 2015年 DaiYu. All rights reserved.
//

#import "UINavigationItem+CustomBackBarItem.h"
#import <objc/runtime.h>

@implementation UINavigationItem (CustomBackBarItem)

+ (void)load
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class class = [self class];

        SEL originalSelector = @selector(backBarButtonItem);
        SEL swizzledSelector = @selector(myBackBarButtonItem);
        
        Method originalMethod = class_getInstanceMethod(class, originalSelector);
        Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
        
        BOOL didAddMethod =
        class_addMethod(class,
                        originalSelector,
                        method_getImplementation(swizzledMethod),
                        method_getTypeEncoding(swizzledMethod));
        
        if (didAddMethod) {
            class_replaceMethod(class,
                                swizzledSelector,
                                method_getImplementation(originalMethod),
                                method_getTypeEncoding(originalMethod));
        } else {
            method_exchangeImplementations(originalMethod, swizzledMethod);
        }
    });
}

static char kCustomBackButtonKey;

- (UIBarButtonItem *)myBackBarButtonItem {
    
    UIBarButtonItem *item = [self myBackBarButtonItem];
    
    if (item) {
        return item;
    }
    
    item = objc_getAssociatedObject(self, &kCustomBackButtonKey);
    
    if (!item) {
        
        item = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:NULL];
        objc_setAssociatedObject(self, &kCustomBackButtonKey, item, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    return item;
}

- (void)dealloc {
    
    objc_removeAssociatedObjects(self);
}

@end
